var app = getApp();
const port = require('../../config.js');
const mainIndex = require('../index.js');
const vipPrivilege = require('../../common/vipPrivilege.js')
const judgeVip = require('../../common/judgeVip.js')

//加载数据
var datalist = function(that, loadtype, condition) {
  var array = that.data.array
  var condition = condition;
  wx.showLoading({
    title: '超努力中...',
  })
  var cardall = that.data.cardall;
  if (loadtype != 'download') {
    that.setData({
      cardall: []
    })
  }
  app.getUserInfo(function(personInfo) {
    var token = personInfo.token;
    var uid = personInfo.uid;
    condition.openid = personInfo.openId;
    if(condition.keyword&&condition.keyword != "all"){
      that.setData({
        ziyuanNodody:true
      })
    }
    //上传、获取咖片集信息
    wx.request({
      url: port.CardAll + '?page=' + condition.limit, //请求地址
      header: { //请求头
        "Content-Type": "applciation/json",
        "Authorization": "Bearer " + token
      },
      data: {
        condition
      },
      method: "post", //get为默认方法/POST
      success: function(res) {
        if (res.data.status == 'success') {
          if (loadtype == 'load' || loadtype == 'download') {
            var cardallArray = new Array();
            cardallArray = cardall;
          } else if (loadtype == 'search') {
            var cardallArray = new Array();
            cardallArray = [];
          }

          for (var i = 0; i < res.data.data.data.length; i++) {
            for (var j in res.data.data.data[i]) {
              if (res.data.data.data[i][j] == null) {
                res.data.data.data[i][j] = ""
              }
            }
            cardallArray.push(res.data.data.data[i]);
          }
          wx.hideToast()
          that.setData({
            count: res.data.data.total,
            cardall: cardallArray,
            searchHistory: res.data.search_data,
            nobody: false,
            whefillziyuan: false,
          })
          wx.hideLoading()
          wx.hideToast()
        } else {
          wx.hideLoading()
          wx.hideToast()
          if (that.data.ziyuanNodody){
            that.setData({
              cardall: [],
              searchHistory: res.data.search_data,
              whefillziyuan: true,
              nobody:false,
            })
          }else{
            that.setData({
              cardall: [],
              searchHistory: res.data.search_data,
              nobody: true,
              whefillziyuan: false,
            })
          }
        }
      },
      fail: function(err) {}, //请求失败
      complete: function(suc) { //请求完成后执行的函数
      }
    })
    //获取行业列表
    wx.request({
      url: port.CardIndustry, //请求地址
      header: { //请求头
        "Content-Type": "applciation/json",
        "Authorization": "Bearer " + token,
      },
      method: "get", //get为默认方法/POST
      success: function(res) {
        if (res.data.status == 'success') {
          for (var i = 0; i < res.data.data.length; i++) {
            array.push(res.data.data[i]['name'])
          }
          that.setData({
            array: array
          })
        }
      },
      fail: function(err) {}, //请求失败
      complete: function(suc) { //请求完成后执行的函数
      }
    })
  })
};
Page({
  data: {
    openid: '', //交换信息
    cardid: '',
    plus_cardid: '',
    formid: '',
    apply_text: '',
    uid: '',
    card: [], //申请交换咖片信息
    cardall: [], //咖片集信息
    region: "全部地区", //地区选择
    province: '全部地区',
    city: '全部地区',
    county: '全部地区',
    index: 0, //行业列表索引
    array: ['全部行业'], //行业列表
    industry: '全部行业', //选择的行业
    search: '', //搜索信息
    showModal: false,
    showSearch: false,
    showFilter: false,
    imgPath: port.imgPath, //照片路径
    animationBox: "",
    animationBox1: "",
    animationText: "",
    animationText1: "",
    aindex: -1,
    findID: '1',
    limit: 1,
    count: 0,
    searchHistory: [],
    searchRecommend: ["总经理", "浙江魅智网络科技有限公司", "杭州", "汽车行业", "创始人", "上海", "互联网", "阿里巴巴", "马云", "123123"],
    keyword: '',
    keywordSelected: '',
    libraryCheck: 0,
    prompt: 1,
    indexShuttle: mainIndex.indexShuttle, //跳转分包shuttle统一路径
    indexMessage: mainIndex.indexMessage, //跳转分包message统一路径
    indexCenter: mainIndex.indexCenter, //跳转分包center统一路径
    whefixed: 'fixed', //head层级
    zExIndex: 8, //交换申请按钮层级
    zFitIndex: 20, //筛选层级
    zSeaIndex: 20, //搜索层级
    vipTip: false, //是否需要提示成为会员
    vipTipContent: '', //成为会员弹窗提示内容
    tipknow: false, //弹窗提示
    vlogo: false, //企业认证logo
    nomoreTipImg: '/images/btn_choose_normal@3x.png', //不再提醒图标
    nomoreTip: false, //设置不再提醒
    showDeduct: false, //是否展示扣除积分弹窗
    showdeduct: false, //是否应当展示扣除积分弹窗
    hisCid: '', //查看名片的cid   
    nobody: false, //没有用户时展示
    wangziyuan: ['全部资源', '需要我的', '我需要的'],
    ziyuanselected: '全部资源',
    whefillziyuan: false,   //未匹配到资源时提示去优化资源
    ziyuanNodody: false,    //是否是判断资源的条件
  },
  //关闭扣除积分弹窗
  closeDeduct: function() {
    var that = this;
    that.setData({
      showDeduct: false
    })
    var nomoreTip = that.data.nomoreTip;
    if (nomoreTip) {
      wx.setStorage({
        key: 'showdeduct',
        data: 1,
      })
      that.setData({
        showdeduct: false
      })
    }
  },
  becomeVip: function() {
    var that = this;
    that.setData({
      vipTip: true,
      vipTipContent: '成为尊享会员\n享受更多专属福利\n还能在人脉圈优先展示哦~'
    })
  },
  //跳转会员中心
  vipCenter: function() {
    var that = this;
    var cardid = that.data.cardid
    if (!cardid) {
      wx.showToast({
        icon: 'success',
        image: '/images/error.png',
        title: '请先添加名片',
      })
    } else {
      var indexShuttle = that.data.indexShuttle;
      wx.navigateTo({
        url: indexShuttle + '/vipCenter/vipCenter',
      })
    }
  },

  //切换不再提醒
  nomoreTip: function(option) {
    var that = this;
    var nomoreTip = option.target.dataset.nomoretip;
    var nomoreTipImg = that.data.nomoreTipImg;
    if (nomoreTip == false) {
      nomoreTip = true;
      nomoreTipImg = '/images/btn_choose_selected@3x.png'
    } else {
      nomoreTip = false;
      nomoreTipImg = '/images/btn_choose_normal@3x.png'
    }
    that.setData({
      nomoreTip: nomoreTip,
      nomoreTipImg: nomoreTipImg
    })
  },
  //关闭成为vip提示
  cancelVipTip: function() {
    var that = this;
    that.setData({
      vipTip: false,
      tipknow: false
    })
  },
  //关键词筛选检查
  keywordSelected: function(e) {
    var that = this;
    if (e.detail.value == 0) {
      that.setData({
        keywordNum: 'all',
        ziyuanselected: '全部资源'
      });
    } else {
      if (e.detail.value == 1) {
        var ziyuanselected = '需要我的';
      } else if (e.detail.value == 2) {
        var ziyuanselected = '我需要的';
      }
      that.setData({
        keywordNum: e.detail.value,
        ziyuanselected: ziyuanselected
      });
    }
    that.filterSubmit();
  },
  //交换申请
  exchange: function(e) {
    console.log(e)
    var that = this;
    //显示申请消息输入框
    this.setData({
      showModal: true
    })
    //设置被请求者cardid
    that.setData({
      plus_cardid: e.currentTarget.id,
      card: that.data.cardall[e.currentTarget.dataset.id]
    })
  },

  //判断长度
  chargeString: function(value) {
    var value = value;
    var strLength = 0;
    for (var i = 0; i < value.length; i++) {
      var type = value.charCodeAt(i)
      if (type >= 19968 && type <= 40869) { //为中文字符
        strLength = strLength + 2;
      } else if (type >= 48 && type <= 57) { //为数字字符
        strLength++;
      } else if (type >= 65 && type <= 122) { //为英文字符
        strLength++;
      } else { //其他字符
        strLength++;
      }
    }
    return strLength;
  },
  formsubmit: function(e) {
    var that = this
    // 设置表单信息
    var liuyan = that.chargeString(e.detail.value.addMsg);
    if (liuyan > 68) {
      wx.showToast({
        title: '留言不可超过30个字哦~',
        icon: 'none',
        mask: true,
        duration: 1500
      })
      return
    }
    that.setData({
      formid: e.detail.formId,
      apply_text: e.detail.value.addMsg
    })
    //发送申请请求
    app.getUserInfo(function(personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      //发送请求交换信息
      wx.request({
        url: port.CardApply,
        method: 'POST',
        data: {
          openid: personInfo.openId,
          cardid: that.data.cardid,
          plus_cardid: that.data.plus_cardid,
          formid: that.data.formid,
          apply_text: that.data.apply_text,
        },
        header: {
          //data为'pageSize=1&pageNum=10'类时，设置参数内容类型为x-www-form-urlencoded
          'content-type': 'application/json',
          "Authorization": "Bearer " + token
        },
        success: function(res) {
          that.setData({
            showModal: false
          });
          wx.showToast({
            title: res.data.message,
          })
        }
      })
    })
  },
  showDetail: function(e) {
    var that = this;
    var animationText = this.animationText;
    animationText.opacity(0).step();
    this.setData({
      animationText: animationText.export(),
    })
    this.setData({
      aindex: e.currentTarget.dataset.id,
    })

    var animationBox = this.animationBox;
    animationBox.height("650rpx").step();
    var animationBox1 = this.animationBox1;
    animationBox1.height("270rpx").step();
    this.setData({
      animationBox: animationBox.export(),
      animationBox1: animationBox1.export()
    })
    animationText.opacity(1).step();
    this.setData({
      animationText: animationText.export(),
    })
  },
  hideDetail: function(e) {
    this.setData({
      aindex: -1,
    })
    var animationBox = this.animationBox;
    animationBox.height("270rpx").step();
    this.setData({
      animationBox: animationBox.export(),
    })
    var animationText = this.animationText;
    animationText.opacity(0).step();
    this.setData({
      animationText: animationText.export(),
    })

  },
  goView: function(e) {
    //判断会员特权
    var that = this;
    var cid = e.currentTarget.id;
    var showDeduct = that.data.showDeduct; //是否展示扣除积分弹窗
    that.setData({
      hisCid: cid
    })
    app.getUserInfo(function(personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      judgeVip.judgeVip(token, uid, function(result) {
        if (result) {
          that.viewPreview()
        } else {
          // if (!that.data.showdeduct) {
          //   that.viewPreview()
          // } else {
          //   that.setData({
          //     showDeduct: true
          //   })
          // }
          that.viewPreview()
        }
      })
    })



  },
  //弹窗扣除积分，继续查看事件
  confirmLook: function() {
    var that = this;
    var nomoreTip = that.data.nomoreTip;
    that.viewPreview();
    if (nomoreTip) {
      wx.setStorage({
        key: 'showdeduct',
        data: 1,
      })
      that.setData({
        showdeduct: false
      })
    }
    that.setData({
      showDeduct: false
    })
  },
  //跳转名片详情
  viewPreview: function() {
    var that = this;
    var cid = that.data.hisCid;
    app.getUserInfo(function(personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      vipPrivilege.vipPrivilege(token, uid, cid, 'look', function(result) {
        if (result == 'vip-deficiency') { //VIP权限上限已达，但积分不足
          wx.showToast({
            title: '今天查看名片已达上限咯~积分不足',
          })
          that.setData({
            tipknow: true,
            vipTipContent: '您今日查看的次数已用完，\n积分也不足咯~\n明天再来看吧~'
          })
        } else if (result == 'deficiency') { //非会员，且积分不足
          that.setData({
            vipTip: true,
            vipTipContent: '您的积分不足喽~\n成为会员吧！\n获取更多特权，还有超多积分！'
          })
        } else if (result == 'success') { //成功
          wx.request({
            url: port.CardMy, //请求地址
            header: { //请求头
              "Content-Type": "applciation/json",
              "Authorization": "Bearer " + token
            },
            data: {
              'uid': uid
            },
            method: "post", //get为默认方法/POST
            success: function(res) {
              if (res.data.status == 'success') {
                var my = 0;
                if (cid == that.data.cardid) {
                  my = 1;
                }
                var indexShuttle = that.data.indexShuttle;
                wx.navigateTo({
                  url: '/pages/index/preview?cid=' + cid + '&my=' + my,
                })
                wx.hideLoading()
              } else {
                wx.showToast({
                  icon: 'none',
                  title: '创建了名片就可以看了哦~~',
                })
              }
            },
            fail: function(err) {
              wx.hideLoading()
            }, //请求失败
            complete: function(suc) { //请求完成后执行的函数
            }
          })
        } else { //系统出错
          wx.showToast({
            title: '查看失败，请重试',
          })
        }
      });
    })
  },
  //上拉加载
  download: function() {
    var that = this;
    if (that.data.cardall.length != that.data.count) {
      // wx.showToast({
      //   title: '加载中...',
      //   icon: 'loading',
      //   mask: true,
      // })
      that.setData({
        limit: that.data.limit + 1
      })
      var datas = {
        'where': that.data.region,
        'soso': that.data.search,
        'industry': that.data.industry,
        'type': that.data.findID,
        'limit': that.data.limit
      };
      datalist(that, 'download', datas)
    } else {
      wx.showToast({
        title: '没有了',
        icon: 'none',
        // mask:true,
        duration: 900,
        success: function() {}
      })
    }
  },
  //筛选
  goFilter: function() {
    this.setData({
      showFilter: true,
    })
  },
  //改变地区
  bindRegionChange: function(e) {
    var that = this;
    if (e.detail.value[1] == "全部地区") {
      that.setData({
        region: e.detail.value[0]
      })
    } else if (e.detail.value[2] == "全部地区") {
      that.setData({
        region: e.detail.value[1]
      })
    } else {
      that.setData({
        region: e.detail.value[2]
      })
    }
    that.setData({
      province: e.detail.value[0],
      city: e.detail.value[1],
      county: e.detail.value[2],
    })
    that.filterSubmit();
  },
  //改变行业
  workChange: function(e) {
    var that = this;
    var array = that.data.array;
    that.setData({
      index: e.detail.value,
      industry: array[e.detail.value]
    })
    that.filterSubmit();
  },
  //筛选提交
  filterSubmit: function() {
    var that = this;
    that.setData({
      limit: 1
    })
    var datas = {
      'where': that.data.region,
      'soso': that.data.search,
      'industry': that.data.industry,
      'type': that.data.findID,
      'limit': that.data.limit,
      'keyword': that.data.keywordNum
    };
    datalist(that, 'search', datas);
    that.setData({
      showFilter: false
    })
  },
  //取消筛选
  cancelFilter: function() {
    this.setData({
      showFilter: false
    })
  },
  //搜索
  searchFocus: function() {
    this.setData({
      showSearch: true,
    })
  },
  cancelSearch: function() {
    var that = this;
    that.setData({
      showSearch: false
    })
    that.search()

  },
  searchInput: function(e) {
    var that = this;
    that.setData({
      search: e.detail.value,
    })
  },
  search: function() {
    var that = this;
    that.setData({
      limit: 1
    })
    var datas = {
      'where': that.data.region,
      'soso': that.data.search,
      'industry': that.data.industry,
      'type': that.data.findID,
      'limit': that.data.limit
    };
    datalist(that, 'search', datas);
    that.setData({
      showSearch: false
    })
  },
  //搜索关键词
  keywordSearch: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.id;
    var keyword = that.data.searchHistory[index];
    that.setData({
      keyword: keyword,
      search: keyword,
      showSearch: false,
      limit: 1
    })
    var datas = {
      'where': that.data.region,
      'soso': that.data.search,
      'industry': that.data.industry,
      'type': that.data.findID,
      'limit': that.data.limit
    };
    datalist(that, 'search', datas);
  },
  //删除关键词
  searchDelete: function() {
    var that = this;
    app.getUserInfo(function(personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      //上传、获取咖片集信息
      wx.request({
        url: port.SearchDel, //请求地址
        header: { //请求头
          "Content-Type": "applciation/json",
          "Authorization": "Bearer " + token
        },
        data: {
          user: uid,
        },
        method: "post", //get为默认方法/POST
        success: function(res) {
          that.setData({
            searchHistory: []
          })
        },
        fail: function(err) {}, //请求失败
        complete: function(suc) { //请求完成后执行的函数
        }
      })
    })
  },
  //搜索推荐词
  recommendSearch: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.id;
    var keyword = that.data.searchRecommend[index];
    that.setData({
      keyword: keyword,
      search: keyword,
      showSearch: false,
      limit: 1
    })
    var datas = {
      'where': that.data.region,
      'soso': that.data.search,
      'industry': that.data.industry,
      'type': that.data.findID,
      'limit': that.data.limit
    };
    datalist(that, 'search', datas);
  },
  searchRefresh: function() {
    console.log("hahaha");
  },
  //申请界面
  showDialogBtn: function() {
    this.setData({
      showModal: true
    })
  },
  hideModal: function() {
    this.setData({
      showModal: false
    });
  },

  /**
   *生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu();
    var that = this;

    //判断是否首次进入
    var libraryCheck = wx.getStorage({
      key: 'libraryCheck',
      success: function(res) {
        if (res.data == 0) {
          that.setData({
            libraryCheck: 0,
            whefixed: '',
            zFitIndex: 99,
          })
        } else if (res.data == 1) {
          that.setData({
            libraryCheck: 1,
          })
        }
      },
    })
    //判断是否设置不再提醒
    var showdeduct = wx.getStorage({
      key: 'showdeduct',
      success: function(res) {
        if (res.data == 0) {
          that.setData({
            showdeduct: true //缓存判断true：应展示
          })
        } else if (res.data == 1) {
          that.setData({
            showdeduct: false
          })
        }
      },
    })
    //载入动画
    // wx.showToast({
    //   title: '加载中',
    //   icon: 'loading',
    // })
    //实例化动画
    this.animationBox = wx.createAnimation({
      duration: 500,
    })
    this.animationBox1 = wx.createAnimation({
      duration: 500,
    })
    this.animationText = wx.createAnimation({
      duration: 500,
      delay: 400,
    })
    that.comparePerself();
    //加载数据
    var datas = {
      'where': that.data.region,
      'soso': that.data.search,
      'industry': that.data.industry,
      'type': that.data.findID,
      'limit': that.data.limit
    };
    datalist(that, 'load', datas)
  },

  nextPrompt: function(e) {
    var that = this;
    var prompt = e.currentTarget.dataset.prompt;
    if (prompt == 1) {
      prompt = 2;
      that.setData({
        zFitIndex: 20,
        zSeaIndex: 99,
      })
    }
    // else if (prompt == 2) {
    //   prompt = 3
    //   that.setData({
    //     zFitIndex: 20,
    //     zSeaIndex: 20,
    //     zExIndex: 99,
    //   })
    // } 
    else if (prompt == 2) {
      wx.setStorage({
        key: 'libraryCheck',
        data: 1,
      })
    }
    that.setData({
      prompt: prompt
    })
    var libraryCheck = wx.getStorage({
      key: 'libraryCheck',
      success: function(res) {
        if (res.data == 0) {
          that.setData({
            libraryCheck: 0,
          })
        } else if (res.data == 1) {
          that.setData({
            libraryCheck: 1,
            whefixed: 'fixed', //head层级
            zExIndex: 8, //交换申请按钮层级
            zFitIndex: 20, //筛选层级
            zSeaIndex: 20 //搜索层级
          })
        }
      },
    })
  },
  //匹配个人信息
  comparePerself: function() {
    var that = this;
    app.getUserInfo(function(personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      that.setData({
        uid: uid,
      })
      //请求个人信息
      wx.request({
        url: port.Personal, //请求地址
        header: { //请求头
          "Content-Type": "applciation/json",
          "Authorization": "Bearer " + token
        },
        data: {
          uid: uid
        },
        method: "post", //get为默认方法/POST
        success: function(res) {
          if (res.data.status == "success") {
            if (res.data.data1 != null && res.data.data1 != "") {
              that.setData({
                cardid: res.data.data1.id,
                uid: res.data.data1.uid
              })
            } else if (res.data.data2 != null && res.data.data2 != "") {
              that.setData({
                openid: res.data.data2.openid,
              })
            }
          }
        },
        fail: function(err) {}, //请求失败
        complete: function(suc) { //请求完成后执行的函数
        }
      })
    })
  },
  // 跳转到更多信息
  goPermessage: function(){
    var that = this;
    var indexMessage = that.data.indexMessage;
    wx.navigateTo({
      url: indexMessage + '/permessage/permessage?dataId='+ 2,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    that.onLoad();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    wx.showToast({
      title: '刷新中...',
      icon: 'loading',
    })

    var that = this;
    that.setData({
      cardall: []
    })
    var datas = {
      'where': that.data.region,
      'soso': that.data.search,
      'industry': that.data.industry,
      'type': that.data.findID,
      'limit': 1
    };
    //模拟加载
    setTimeout(function() {
      // complete
      datalist(that, 'load', datas)

    }, 1200);
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

})